package app;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import javax.swing.text.Document;
import javax.swing.text.rtf.RTFEditorKit;
import java.util.ArrayList;

public class DocumentManager {
	
	private CLI cli = new CLI(); //Command Line Interpreter
	private db.DatabaseManager db = new db.DatabaseManager();
	
	public DocumentManager()
	{
		//Nothing to be done.
	}
	
	public boolean addDocument()
	{
		//Get all the details about the essay
		String filename = cli.getString("What is the name of the file? ");
		String subject = cli.getString("What is subject of the file? ");
		String author = cli.getString("Who is the author of the file? ");
		String contents;
		if(filename.indexOf("txt") > 0)
			contents = getTxtFileContents(filename);
		else if(filename.indexOf("rtf") > 0)
			contents = getRtfFileContents(filename);
		else {
			System.out.println("Invalid filetype.");
			return false;
		}
		return db.insertDocument(new Essay(subject,author,contents));		
	}
	
	public String getTxtFileContents(String filename)
	{
		BufferedReader file;
		String temp = "", contents = "";
		try{
			file = new BufferedReader(new FileReader("Docs/" + filename));
			temp = file.readLine();
			while(temp != null){
				if(!temp.equals(""))
					contents += temp;
				temp = file.readLine();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return contents;
	}
	
	public String getRtfFileContents(String filename)
	{	
		FileInputStream file = null;
		String contents = "";
		try {
			file = new FileInputStream(filename);
			RTFEditorKit rtf = new RTFEditorKit();
			Document doc = (Document)rtf.createDefaultDocument();
			rtf.read(file,doc,0);
			contents = doc.getText(0, doc.getLength());
		}catch(Exception e){
			e.printStackTrace();
		}
		return contents;
	}
	
	public ArrayList<String> getAllSubjects()
	{
		return db.getAllSubjects();
	}
	
	public ArrayList<Essay> getEssays(String subject)
	{
		return db.getEssays(subject);
	}

}
